import { IPlank } from '@/types';
import { Modal, Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import React, { useState } from 'react';

const log = console.log.bind(null, '[PlankSelect]');

const columns: ColumnsType<IPlank> = [
  {
    title: '编号',
    dataIndex: 'code',
  },
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    title: '产品名称',
    dataIndex: 'productName',
  },
];

interface Props {
  dataSource: IPlank[];
  onConfirm(data: IPlank): void;
}
export const PlankSelect: React.FC<Props> = (props) => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selected, setSelected] = useState<IPlank>();

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = () => {
    if (!selected) {
      alert('未选择数据');
      return;
    }
    log('onConfirm', { selected });
    props.onConfirm(selected);
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <>
      <button onClick={showModal}>板件选择</button>
      <Modal
        title="获取数据"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Table
          rowKey={'code'}
          rowSelection={{
            type: 'radio',
            onSelect(record) {
              setSelected(record);
            },
          }}
          columns={columns}
          dataSource={props.dataSource}
        />
      </Modal>
    </>
  );
};

export default PlankSelect;
